﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using CommonControlLibrary.Common;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Editors.Settings;
using System.Data;
using QueryResource.Common;
using QueryResource.ViewModel;
using DevControlLibrary.Common;

namespace DevControlLibrary.UI.Comparsion
{
    /// <summary>
    /// DataRowDetailedWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataRowDetailedWindow : DXWindow
    {
        private readonly string _tableName = string.Empty;
        private readonly DataFilterColumnEntity[] _columnFilter;
        private readonly DataFilterColumnEntity[] _notColumnFilter;
        private readonly DataComparsionViewModel _viewModel;
        public DataRowDetailedWindow(string tablename, 
            DataFilterColumnEntity[] list,
            DataFilterColumnEntity[] noFilter,
            DataComparsionViewModel viewModel)
        {
            InitializeComponent();
            _tableName = tablename;
            _columnFilter = list;
            _notColumnFilter = noFilter;
            _viewModel = viewModel;
            this.Loaded += DataRowDetailedWindow_Loaded;
        }

        void DataRowDetailedWindow_Loaded(object sender, RoutedEventArgs e)
        {
            BindColumn(_columnFilter);
            BindGrid();
            this.syncData.IsEnabled = false;

            XmlHelper.Instance.SetTheme(this);
        }

        /// <summary>
        /// 绑定列
        /// </summary>
        /// <param name="list"></param>
        private void BindColumn(IEnumerable<DataFilterColumnEntity> list)
        {
            this.sourceGrid.Columns.Clear();
            this.targetGrid.Columns.Clear();
            foreach (DataFilterColumnEntity entity in list)
            {
                DevExpress.Xpf.Grid.GridColumn gc = new DevExpress.Xpf.Grid.GridColumn();
                DevExpress.Xpf.Grid.GridColumn gc1 = new DevExpress.Xpf.Grid.GridColumn();

                gc.FieldName = entity.ColumnName;
                gc1.FieldName = entity.ColumnName;

                string typename = entity.TypeName;
                if (typename == "DATETIME" ||
                    typename == "DATE" ||
                    typename == "TIME" ||
                    typename == "TIMESTAMP")
                {
                    gc.EditSettings = new TextEditSettings {DisplayFormat = "yyyy-MM-dd HH:mm:ss.ffffff"};

                    gc1.EditSettings = new TextEditSettings {DisplayFormat = "yyyy-MM-dd HH:mm:ss.ffffff"};
                }
                this.sourceGrid.Columns.Add(gc);
                this.targetGrid.Columns.Add(gc1);
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindGrid()
        {
            _viewModel.GetTableRowsInfo(_tableName, (t, ds) => {
                if (t == "SOURCE")
                {
                    this.sourceGrid.InvokeEx(() =>
                                                 {
                                                     this.sourceGrid.ItemsSource = ds.Tables[0];
                                                     this.layoutSource.Caption = "源数据-->" + ds.Tables[0].Rows.Count;
                                                 });
                }
                else
                {
                    this.sourceGrid.InvokeEx(() =>
                                                 {
                                                     this.targetGrid.ItemsSource = ds.Tables[0];
                                                     this.layoutTarget.Caption = "目标数据-->" + ds.Tables[0].Rows.Count;
                                                 });
                }
            });
        }
        private void contrastPKData_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            DataTable sourceDT = this.sourceGrid.ItemsSource as DataTable;
            DataTable targetDT = this.targetGrid.ItemsSource as DataTable;
            if (sourceDT != null)
            {
                DataTable editSourceDT = sourceDT.Clone();
                if (targetDT != null)
                {
                    DataTable editTargetDT = targetDT.Clone();

                    string[] pkColumns = _columnFilter.Where(o => o.Primary == "PK").Select(p=>p.ColumnName).ToArray();
                    if (pkColumns.Length == 0)
                    {
                        MessageBoxHelper.Show("所选择的列中没有主键，无法对比。");
                        return;
                    }
                    //先对比每列的数据
                    foreach (DataRow row in targetDT.Rows)
                    {
                        DataRow row1 = row;
                        Func<DataRow, bool> selectFilter = dr => CompareColumn(dr, row1, pkColumns);
                        DataRow sourceRow = sourceDT.AsEnumerable().FirstOrDefault(selectFilter);
                        if (sourceRow == null)
                        {
                            editTargetDT.Rows.Add(row.ItemArray);
                        }
                    }
                    foreach (DataRow row in sourceDT.Rows)
                    {
                        DataRow row1 = row;
                        Func<DataRow, bool> selectFilter = dr => CompareColumn(dr, row1, pkColumns);
                        DataRow targetRow = targetDT.AsEnumerable().FirstOrDefault(selectFilter);
                        if (targetRow == null)
                        {
                            editSourceDT.Rows.Add(row.ItemArray);
                        }
                    }

                    this.sourceGrid.ItemsSource = editSourceDT;
                    this.targetGrid.ItemsSource = editTargetDT;
                    this.layoutSource.Caption = string.Format("源数据[{0}]-->{1}", sourceDT.Rows.Count, editSourceDT.Rows.Count);
                    this.layoutTarget.Caption = string.Format("目标数据[{0}]-->{1}", targetDT.Rows.Count, editTargetDT.Rows.Count);
                }
            }
            this.syncData.IsEnabled = true;
        }
        private void contrastData_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            DataTable sourceDT = this.sourceGrid.ItemsSource as DataTable;
            DataTable targetDT = this.targetGrid.ItemsSource as DataTable;
            if (sourceDT != null)
            {
                DataTable editSourceDT = sourceDT.Clone();
                if (targetDT != null)
                {
                    DataTable editTargetDT = targetDT.Clone();
                    List<string> columns = _columnFilter.Select(column => column.ColumnName).ToList();
                    //先对比每列的数据
                    foreach (DataRow row in targetDT.Rows)
                    {
                        DataRow row1 = row;
                        Func<DataRow, bool> selectFilter = dr => CompareColumn(dr,row1,columns.ToArray());
                        DataRow sourceRow = sourceDT.AsEnumerable().FirstOrDefault(selectFilter);
                        if (sourceRow == null)
                        {
                            editTargetDT.Rows.Add(row.ItemArray);
                        }
                    }
                    foreach (DataRow row in sourceDT.Rows)
                    {
                        DataRow row1 = row;
                        Func<DataRow, bool> selectFilter = dr => CompareColumn(dr, row1, columns.ToArray());
                        DataRow targetRow = targetDT.AsEnumerable().FirstOrDefault(selectFilter);
                        if (targetRow == null)
                        {
                            editSourceDT.Rows.Add(row.ItemArray);
                        }
                    }

                    this.sourceGrid.ItemsSource = editSourceDT;
                    this.targetGrid.ItemsSource = editTargetDT;
                    this.layoutSource.Caption = string.Format("源数据[{0}]-->{1}", sourceDT.Rows.Count,editSourceDT.Rows.Count);
                    this.layoutTarget.Caption = string.Format("目标数据[{0}]-->{1}",targetDT.Rows.Count,editTargetDT.Rows.Count);
                }
            }
            this.syncData.IsEnabled = true;
        }
        private bool CompareColumn(DataRow dr,DataRow row, IEnumerable<string> columns)
        {
            foreach (string column in columns)
            {

                if (dr[column] != null && row[column] != null)
                {
                    if (dr[column].ToString() != row[column].ToString())
                    {
                        return false;
                    }
                }
                else if (dr[column] == null && row[column] == null)
                { return true; }
                else
                    return false;

            }
            return true;
        }

        private void syncData_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            DataTable targetDT = this.targetGrid.ItemsSource as DataTable;
            if (_notColumnFilter.Length > 0)
            {
                DataColumnCustomWindow win = new DataColumnCustomWindow(_notColumnFilter);
                if (win.ShowDialog() == true)
                {
                    _viewModel.TableRowsExport(_tableName, targetDT, win.CustomColumn,() => MessageBoxHelper.ShowMessage("确定是否提交？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK);
                }
            }
            else
            {
                _viewModel.TableRowsExport(_tableName, targetDT, null, () => MessageBoxHelper.ShowMessage("确定是否提交？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK);
            }
        }

        ScrollViewer sv1, sv2;
        private void tableView1_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {

            sv1 = (e.OriginalSource as ScrollViewer);
            if (this.isSyncScrollBar.IsChecked == true)
            {
                if (sv2 != null)
                {
                    sv2.ScrollToHorizontalOffset(e.HorizontalOffset);
                    sv2.ScrollToVerticalOffset(e.VerticalOffset);
                }
            }
        }

        private void tableView2_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            sv2 = (e.OriginalSource as ScrollViewer);
            if (this.isSyncScrollBar.IsChecked == true)
            {
                if (sv1 != null)
                {
                    sv1.ScrollToHorizontalOffset(e.HorizontalOffset);
                    sv1.ScrollToVerticalOffset(e.VerticalOffset);
                }
            }
        }
    }
}
